//配置路由
import Vue from 'vue';
import VueRouter from 'vue-router';

//使用插件
Vue.use(VueRouter)
//当打包构建应用时，JavaScript 包会变得非常大，影响页面加载。
//如果我们能把不同路由对应的组件分割成不同的代码块，然后当路由被访问的时候才加载对应组件，这样就会更加高效。
//路由懒加载！

// import Home from '@/pages/Home';
// import Search from '@/pages/Search';
// import Login from '@/pages/Login';
// import Register from '@/pages/Register'
// import Detail from '@/pages/Detail'
// import AddCartSuccess from '@/pages/AddCartSuccess'
// import ShopCart from '@/pages/ShopCart'
// import Trade from '@/pages/Trade'
// import Pay from '@/pages/Pay'
// import PaySuccess from '@/pages/PaySuccess'
// import Center from '@/pages/Center'
//引入二级路由
// import myCenter from '@/pages/Center/myCenter'
// import groupCenter from '@/pages/Center/groupCenter'
//引入store
import store from '@/store'
//先把VueRouter原型对象的push方法 保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push replace方法
//第一个参数往哪里跳转
//第二个参数 成功回调
//第三个 失败回调
VueRouter.prototype.push = function(location, resolve, reject) {
    if (resolve && reject) {
        //call()调用函数一次
        originPush.call(this, location, resolve, reject)
    }
    else {
        originPush.call(this, location, () => { }, () => { })
    }
}

VueRouter.prototype.replace = function(location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    }
    else {
        originReplace.call(this, location, () => { }, () => { })
    }
}
//配置路由
let router = new VueRouter({

    routes: [
        {
            path: '/center',
            component: () => import("@/pages/Center"),
            meta: { show: true },
            children: [
                {
                    path: 'mycenter',
                    component: () => import("@/pages/Center/myCenter"),
                },
                {
                    path: 'groupcenter',
                    component: () => import("@/pages/Center/groupCenter"),
                },
                {
                    path: '/center',
                    redirect: '/center/mycenter'
                }
            ]
        },
        {
            path: '/paysuccess',
            component: () => import("@/pages/PaySuccess"),
            meta: { show: true },
        },
        {
            path: '/pay',
            component: () => import("@/pages/Pay"),
            meta: { show: true },
            //路由独享守卫
            beforeEnter: (to, from, next) => {
                if (from.path == '/trade') {
                    next()
                } else {
                    next(false)
                }
            }
        },
        {
            path: '/trade',
            component: () => import("@/pages/Trade"),
            meta: { show: true },
            //路由独享守卫
            beforeEnter: (to, from, next) => {
                if (from.path == '/shopcart') {
                    next()
                } else {
                    next(false)
                }
            }
        },
        {
            path: '/shopcart',
            component: () => import("@/pages/ShopCart"),
            meta: { show: true },
        },
        {
            path: '/addcartsuccess',
            component: () => import("@/pages/AddCartSuccess"),
            meta: { show: true },
            name: 'addcartsuccess'
        },
        {
            path: '/detail/:id?',
            component: () => import("@/pages/Detail"),
            meta: { show: true }
        },
        {
            path: '/home',
            component: () => import("@/pages/Home"),
            //配置路由元信息
            meta: { show: true }
        },
        {
            path: '/search/:keyword?',
            component: () => import("@/pages/Search"),
            meta: { show: true },
            name: 'search'

        },
        {
            path: '/login',
            component: () => import("@/pages/Login"),
            meta: { show: false }
        },
        {
            path: '/register',
            component: () => import("@/pages/Register"),
            meta: { show: false }

        },
        {
            path: '*',
            redirect: '/home'
        }

    ],
    //滚动行为
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            //y ：0页面回到最上面
            return { x: 0, y: 0 }
        }
    }
})
//全局守卫 前置守卫（在路由跳转之前进行判断）
router.beforeEach(async (to, from, next) => {
    //to:可以获取到你要跳转到那个路由信息
    //from :可以获取到你从哪个路由而来的信息
    //next ：放行函数 next()放行  next(path)放行到指定路由  next(false);
    // next()
    let token = store.state.user.token;
    //用户信息
    let name = store.state.user.userInfo.name;
    //token有 登录了
    if (token) {
        //去login
        if (to.path == '/login') {
            next('/home')
        } else {
            //不去login 
            //如果有用户名
            if (name) {
                next()
            } else {
                //没有用户信息  派发action让仓库存储信息再跳转
                try {
                    //获取用户信息成功
                    await store.dispatch('getUserInfo');
                    next()
                } catch (error) {
                    //token失效  重新登录
                    //清除token
                    await store.dispatch('logout')
                    next('/login')
                }
            }
        }
    } else {
        //未登录不能去个人中心 交易 支付
        let toPath = to.path
        if (toPath.indexOf('/center') !== -1 || toPath.indexOf('/pay') !== -1 || toPath.indexOf('/trade') !== -1) {
            //把未登录想去没去的的信息，存储在地址栏中
            next('/login?redirect=' + toPath)
        } else {
            next()
        }
    }
})

export default router